/*
 * Serum
 *
 * @license      GNU Lesser General Public Licence see LICENCE-LGPL file or http://www.gnu.org/licenses/lgpl.html
 */

Ext.namespace('Serum', 'Serum.Panel', 'Serum.Form');

Serum.Installer = function() {
    var _instance = null;

    var __construct = function() {
        return {
            /**
             * Event listener instance
             */
            eventListener: null,

            /**
             * Serum initialisation
             */
            init: function() {
                Ext.QuickTips.init();

                // GUI
                new Serum.Panel.Installer();
            }
        }
    };

    return {
        /**
         * Returns instance
         *
         * @return  {Serum.App}     Instance
         */
        get: function() {
            if (_instance === null) {
                _instance = __construct();
            }
            return _instance;
        }
    };
}();


Serum.Panel.Installer = Ext.extend(Ext.Viewport, {

    /**
     * Constructor
     */
    constructor: function() {
        Serum.Panel.Installer.superclass.constructor.call(this, {});

        /*
         * Displays window
         */
        var win = new Ext.Window({
            closable:   false,
            resizable:  false,
            border:     false,
            shadow:     false,
            items:      new Serum.Form.Installer()
        });

        win.show();
    }
});

Serum.Form.Installer = Ext.extend(Ext.FormPanel, {

    /**
     * Constructor
     */
   constructor: function() {
       Serum.Form.Installer.superclass.constructor.call(this, {
            url:            'validation.php',
            frame:          true,
            monitorValid:   true,

            //title :         'Informations de connexion à la base de données',
            items :         [
                new Ext.form.FieldSet({
                    title:          'Database',
                    collapsible:    true,
                    autoHeight:     true,

                    items:          [
                        {
                            xtype :         'combo',
                            name :          'fieldAdapter',
                            hiddenName:     'fieldAdapter',
                            displayField :  'name',
                            fieldLabel :    'DBMS',
                            allowBlank:     false,
                            editable:       false,
                            forceSelection: true,
                            mode:           'local',
                            valueField:     'adapter',
                            value:          'mysql',
                            triggerAction:  'all',
                            store:          new Ext.data.SimpleStore({
                                                fields: ['adapter', 'name'],
                                                data: [['mysql',    'MySQL'     ],
                                                       ['sqlite',   'SQLite'    ],
                                                       ['pgsql',    'PostgreSQL'],
                                                       ['oci',      'OCI'       ],
                                                       ['oci8',     'OCI8'      ],
                                                       ['oracle',   'Oracle'    ],
                                                       ['mssql',    'MSSQL'     ],
                                                       ['dblib',    'DBlib'     ],
                                                       ['firebird', 'Firebird'  ],
                                                       ['informix', 'Informix'  ],
                                                       ['mock',     'Mock'      ]]
                                            })
                        }, {
                            name :          'fieldHost',
                            xtype:          'textfield',
                            fieldLabel :    'Host',
                            value:          'localhost',
                            allowBlank:     false
                        }, {
                            name :          'fieldUsername',
                            xtype:          'textfield',
                            fieldLabel :    'Login',
                            value:          'root',
                            allowBlank:     false
                        }, {
                            name :          'fieldPassword',
                            xtype:          'textfield',
                            fieldLabel :    'Password',
                            inputType:      'password',
                            allowBlank:     true
                        }, {
                            name :          'fieldDbname',
                            xtype:          'textfield',
                            fieldLabel :    'Schema name',
                            allowBlank:     false
                        }, {
		                	name :          'fieldEmail',
		                	xtype:          'textfield',
		                	fieldLabel :    'Email',
		                	allowBlank:     false
		                }
                    ]
                }),

                new Ext.form.FieldSet({
                    title:          'Subversion',
                    collapsible:    true,
                    collapsed:      false,
                    autoHeight:     true,

                    items:          [
                        {
                            name :          'svn_source',
                            xtype:          'textfield',
                            fieldLabel :    'Repository',
                            value:          '',
                            allowBlank:     true
                        }, {
                            name :          'svn_login',
                            xtype:          'textfield',
                            fieldLabel :    'Login',
                            value:          '',
                            allowBlank:     true
                        }, {
                            name :          'svn_password',
                            xtype:          'textfield',
                            inputType:      'password',
                            fieldLabel :    'Password',
                            allowBlank:     true
                        }, {
                            xtype :         'combo',
                            name :          'svn_client',
                            hiddenName:     'svn_client',
                            displayField :  'name',
                            fieldLabel :    'Client',
                            allowBlank:     true,
                            editable:       false,
                            forceSelection: true,
                            mode:           'local',
                            valueField:     'adapter',
                            value:          'svn',
                            triggerAction:  'all',
                            store:          new Ext.data.SimpleStore({
                                                fields: ['adapter', 'name'],
                                                data: [['svn',      'Svn'           ],
                                                       ['tortoise', 'Tortoise Svn'  ]]
                                            })
                        }, {
                            name :          'svn_binary',
                            xtype:          'textfield',
                            value:          '/usr/bin/svn',
                            fieldLabel :    'Binary',
                            allowBlank:     true
                        }]
                })
            ],
            buttons :       [
                {
                    text:           'Valider',
                    formBind:       true,

                    handler: function() {
                        this.getForm().submit({
                            method:    'POST',
                            waitTitle: 'Validation',
                            waitMsg:   'Envoi des données en cours...',

                            success: function(form, action) {
                                /*
                                 * Redirects to Serum login
                                 */
                                 Ext.MessageBox.show({
                                    title:      'Installing...',
                                    msg:        'Serum installation is processing...',
                                    width:      250,
                                    wait:       true,
                                    waitConfig: { interval: 100 }
                                });

                                var jsonResponse = Ext.util.JSON.decode(action.response.responseText);
                                window.location = jsonResponse.page;
                            },

                            failure: function(form, action) {

                                if (action.failureType == 'server') {
                                    /*
                                     * Server error
                                     */
                                    var jsonResponse = Ext.util.JSON.decode(action.response.responseText);

                                    if (typeof jsonResponse.errors.reason !== 'undefined') {
                                        Ext.Msg.show({
                                           title:   'Erreur de connexion',
                                           msg:     '<br />' + jsonResponse.errors.reason,
                                           modal:   true,
                                           icon:    Ext.MessageBox.ERROR,
                                           buttons: Ext.MessageBox.OK
                                        });

                                    } else {

                                        for (var error in jsonResponse.errors.fields) {
                                            var field = this.find('name', error)[0];

                                            if (typeof field !== 'undefined' && field instanceof Ext.form.Field) {
                                                field.markInvalid(jsonResponse.errors.fields[error]);
                                            }
                                        }
                                    }

                                } else {
                                    /*
                                     * Other error
                                     */
                                    Ext.Msg.alert('Warning!', 'Authentication server is unreachable : ' + action.response.responseText);
                                }
                            },

                            scope: this
                        });
                    },
                    scope: this
                }]
        });
   }
});

Ext.onReady(function() {
    Serum.Installer.get().init();
});